package main

import (
	"github.com/astaxie/beego/config"
	"log"
	"net"
	"ssrt/helper"
)

func localToRemote() {

	// 获取配置文件
	conf, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		log.Fatalf("配置文件错误: %v", err)
	}
	username := conf.String("uat-rabbitmq::username")
	password := conf.String("uat-rabbitmq::password")
	addr := conf.String("uat-rabbitmq::addr")
	localAddr := conf.String("uat-rabbitmq::localAddr")
	remoteAddr := conf.String("uat-rabbitmq::remoteAddr")

	// 设置跳板机
	clientConfig := helper.SetClientConfig(username, password)

	// 设置本地监听端口
	localListener, err := net.Listen("tcp", localAddr)
	if err != nil {
		log.Fatalf("net.Listen failed: %v", err)
	}

	for {
		// 开启一个本地连接，这里会停下来
		localConn, err := localListener.Accept()
		if err != nil {
			log.Fatalf("listen.Accept failed: %v", err)
		}

		go func() {
			// 拨号给跳板机
			client := helper.OpenClient(addr, clientConfig)

			// 获取远程连接
			remoteConn, err := client.Dial("tcp", remoteAddr)
			if err != nil {
				log.Fatalf("client.Dial failed: %v", err)
			}

			// 互相拷贝连接，实现转发
			go helper.CopyConn(localConn, remoteConn)
			go helper.CopyConn(remoteConn, localConn)
		}()
	}
}

func remoteToLocal() {

	// 获取配置文件
	conf, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		log.Fatalf("配置文件错误: %v", err)
	}
	username := conf.String("uat-git::username")
	password := conf.String("uat-git::password")
	addr := conf.String("uat-git::addr")
	localAddr := conf.String("uat-git::localAddr")
	remoteAddr := conf.String("uat-git::remoteAddr")

	// 设置跳板机
	clientConfig := helper.SetClientConfig(username, password)

	// 获取本地连接
	localConn, err := net.Dial("tcp", localAddr)
	if err != nil {
		log.Fatalf("net.Dial failed: %v", err)
	}

	for {
		// 拨号给跳板机
		client := helper.OpenClient(addr, clientConfig)

		// 设置远程监听端口
		remoteListener, err := client.Listen("tcp", remoteAddr)
		if err != nil {
			log.Fatalf("net.Listen failed: %v", err)
		}

		// 开启一个远程连接，这里会停下来
		remoteConn, err := remoteListener.Accept()
		if err != nil {
			log.Fatalf("listen.Accept failed: %v", err)
		}

		go func() {
			// 互相拷贝连接，实现转发
			go helper.CopyConn(localConn, remoteConn)
			go helper.CopyConn(remoteConn, localConn)
		}()
	}
}
